package com.wgn.reportquery.serlet;

//导入必需的 java 库
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.wgn.reportquery.cons.Const;
import com.wgn.reportquery.dao.ImportDaoImple;
import com.wgn.reportquery.http.QueryHttpClient;
import com.wgn.reportquery.model.Query;
import com.wgn.reportquery.model.ReportDate;
import com.wgn.reportquery.model.Reportdata;
import com.wgn.reportquery.model.User_SK;
import com.wgn.reportquery.rj.model.RJReport;
import com.wgn.reportquery.rj.model.RJReportInfo;
import com.wgn.reportquery.service.ImportService;
import com.wgn.reportquery.model.InputObj;
import com.wgn.reportquery.module.ChartReport;
import com.wgn.reportquery.service.QueryService;
import com.wgn.reportquery.service.SignService;
import com.wgn.reportquery.thread.ImportSkThread;
import com.wgn.reportquery.utils.ImageRequest;
import com.wgn.reportquery.utils.Importer;
import com.wgn.reportquery.utils.ReportUtils;

//扩展 HttpServlet 类
public class DoSomequery extends HttpServlet {

	private static final long serialVersionUID = 2L;

	protected void doPostt(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * 上传数据及保存文件
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = (String) request.getSession().getAttribute(
				Const.userName);
		String passwd = (String) request.getSession()
				.getAttribute(Const.passwd);
		String querytype = request.getParameter("querytype");
		System.out.println("操作类型:" + querytype);
		if (null == username) {

			getServletContext().getRequestDispatcher("/jsp/signin.jsp")
					.forward(request, response);

			return;
		}
		if (Const.LOOK4TYPE.equalsIgnoreCase(querytype)) {
			String querytypevalue = request.getParameter("querytypevalue");
			if (null != querytypevalue)
				querytypevalue = ReportUtils.getChinese(querytypevalue);

			System.out.println("模糊查询的类别为" + querytypevalue
					+ this.getClass().getName());
			QueryService q = new QueryService(username);
			String listhtml = q.look4type(querytypevalue, passwd);
			response.setContentType("text/html;charset=utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(listhtml);
		} else if (Const.bindrj.equalsIgnoreCase(querytype)) {
			QueryService q = new QueryService(username);
			String RJUSERNAME = request.getParameter("RJUSERNAME");
			String RJPASSWD = request.getParameter("RJPASSWD");
			String result = q.bindrj(RJUSERNAME, RJPASSWD);
			response.setContentType("text/html;charset=utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(result);

		} else if ("bindsk".equalsIgnoreCase(querytype)) {
//			QueryService q = new QueryService(username);
			QueryHttpClient skq = (QueryHttpClient) request.getSession()
					.getAttribute("skq");
			String SKUSERNAME = request.getParameter("SKUSERNAME");
			String SKPASSWD = request.getParameter("SKPASSWD");
			String SKUSERNAMENO64 = request.getParameter("SKUSERNAMENO64");
			String SKPASSWDNO64 = request.getParameter("SKPASSWDNO64");
			String logincertCode = request.getParameter("logincertCode");
			String result = skq.bindSK(logincertCode, SKUSERNAME, SKPASSWD,
					SKUSERNAMENO64, SKPASSWDNO64);
			PrintWriter pw = response.getWriter();
			pw.write(result);
			return;
			/*
			 * String result = q.bindsk(SKUSERNAME, SKPASSWD, logincertCode,
			 * skq); if ("ok".equalsIgnoreCase(result)) {
			 * request.getSession().removeAttribute("skq");
			 * 
			 * } response.setContentType("text/html;charset=utf-8"); PrintWriter
			 * pw = response.getWriter(); pw.write(result);
			 */

		} else if (Const.skinput.equalsIgnoreCase(querytype)) {
			QueryService q = new QueryService(username);
			boolean checkcard = q.checkIfBindSkCards();
			if (!checkcard)// 么有绑定卡
			{
				getServletContext().getRequestDispatcher("/jsp/regist_sk.jsp?")
						.forward(request, response);
				return;
			}
			String year = ReportUtils.getYears();
			String month = ReportUtils.getMonths();
			String day = ReportUtils.getDays();
			List<String> list = q.getCards();
			String cards = ReportUtils.getCardStr(list);
			String hostlist = q.getHostpitalHtml();
			request.setAttribute("hostlist", hostlist);
			request.setAttribute("username", username);
			request.setAttribute("cards", cards);
			request.setAttribute("year", year);
			request.setAttribute("month", month);
			request.setAttribute("day", day);

			getServletContext().getRequestDispatcher("/jsp/skinput.jsp?")
					.forward(request, response);
			// 20170604增加sk批量导入线程

		
			Query qq = new Query();
			qq.setUsername(username);
			qq.setPasswd(passwd);//直接用本站用户名，会在login的方法里去把sk的用户名密码查出来
			ReportDate date = ReportUtils.getDate("-");
			String start_time = date.getStart();// 往前推一年
			String end_time = date.getEdn();// 当前日期
			qq.setStart_time(start_time);
			qq.setEnd_time(end_time);

			InputObj obj = new InputObj("sk", username, null, null, null, null);
			obj.setCardlist(q.getCards());
			obj.setQq(qq);
			q.runImport(obj);
		}
		/*
		 * else if ("verifycode".equalsIgnoreCase(querytype)) {// // 获得验证码
		 * String random = request.getParameter("id");
		 * 
		 * QueryHttpClient skq = new QueryHttpClient(username);
		 * request.getSession().setAttribute("skq", skq); String wholeurl =
		 * Const.skverifycodeurl.replace("##", random);
		 * response.setContentType("image/*"); // 设置返回的文件类型
		 * skq.getImgSk(wholeurl,response.getOutputStream());
		 * 
		 * }
		 */
		else if (Const.rjinput.contentEquals(querytype)) {
			// 跳转到仁济的报告查询页面

			QueryService q = new QueryService(username);

			boolean checkcard = q.checkIfBindRjCards();
			if (!checkcard)// 么有绑定卡
			{
				// String message = "";
				// request.setAttribute("message", message);
				// String reg = "regist_rj.jsp";
				// request.setAttribute("reg", reg);
				getServletContext().getRequestDispatcher("/jsp/regist_rj.jsp?")
						.forward(request, response);
				return;
			}
			String year = ReportUtils.getYears();
			String month = ReportUtils.getMonths();
			String day = ReportUtils.getDays();
			List<String> cardlist = q.getRjCards();// 医保卡
			String cards = ReportUtils.getCardStr(cardlist);

			request.setAttribute("username", username);
			request.setAttribute("cards", cards);
			request.setAttribute("year", year);
			request.setAttribute("month", month);
			request.setAttribute("day", day);
			getServletContext().getRequestDispatcher("/jsp/rjinput.jsp?")
					.forward(request, response);
			// 20170531起一个线程更新数据
			q.runImport(new InputObj("rj", username, cardlist));

		} else if (Const.QUERYRJ.endsWith(querytype)) {
			String kh = request.getParameter("cards");
			// String start_time = request.getParameter("datestart");
			// String end_time = request.getParameter("dateend");
			String datestart_year = request.getParameter("datestart_year");
			String datestart_month = request.getParameter("datestart_month");
			if (datestart_month.length() < 2)
				datestart_month = "0" + datestart_month;
			String datestart_day = request.getParameter("datestart_day");
			if (datestart_day.length() < 2)
				datestart_day = "0" + datestart_day;
			String start_time = datestart_year + datestart_month
					+ datestart_day;
			String dateend_year = request.getParameter("dateend_year");
			String dateend_month = request.getParameter("dateend_month");
			if (dateend_month.length() < 2)
				dateend_month = "0" + dateend_month;
			String dateend_day = request.getParameter("dateend_day");
			if (dateend_day.length() < 2)
				dateend_day = "0" + dateend_day;
			String end_time = dateend_year + dateend_month + dateend_day;
			SignService ss = new SignService();
			List<RJReportInfo> reportlist = ss.getReport(username, start_time,
					end_time, kh);
			String reportHtml = ReportUtils.getRJQuerListHtml(reportlist);
			request.setAttribute("reportHtml", reportHtml);
			String outinfo = "查询期间:" + start_time + "~" + end_time;
			request.setAttribute("outinfo", outinfo);
			getServletContext().getRequestDispatcher("/jsp/queryrj.jsp")
					.forward(request, response);
		} else if ("skreport".equalsIgnoreCase(querytype)) {
			String url = request.getParameter("url");
			System.out.println("sk报告路径" + url);
			String wholeurl = Const.SK_REPORT_URL + url;
			ImportSkThread importSkThread = (ImportSkThread) request
					.getSession().getAttribute("importSkThread");
			QueryHttpClient client = importSkThread.getClient();
			String reporthtml = client.getHtmlSk(wholeurl);
			System.out.println(reporthtml);
			request.setAttribute("signlereport", reporthtml);
			getServletContext().getRequestDispatcher("/jsp/signlequerysk.jsp")
					.forward(request, response);

		} else if ("QUERYSK".equalsIgnoreCase(querytype)) {// sk获取报告列表
			String kh = request.getParameter("cards");
			// String start_time = request.getParameter("datestart");
			// String end_time = request.getParameter("dateend");
			String datestart_year = request.getParameter("datestart_year");
			String datestart_month = request.getParameter("datestart_month");
			if (datestart_month.length() < 2)
				datestart_month = "0" + datestart_month;
			String datestart_day = request.getParameter("datestart_day");
			if (datestart_day.length() < 2)
				datestart_day = "0" + datestart_day;
			String start_time = datestart_year + "-" + datestart_month + "-"
					+ datestart_day;
			String dateend_year = request.getParameter("dateend_year");
			String dateend_month = request.getParameter("dateend_month");
			if (dateend_month.length() < 2)
				dateend_month = "0" + dateend_month;
			String dateend_day = request.getParameter("dateend_day");
			if (dateend_day.length() < 2)
				dateend_day = "0" + dateend_day;
			String end_time = dateend_year + "-" + dateend_month + "-"
					+ dateend_day;
			String hospital_id = request.getParameter("hospital");

			Query qq = new Query(kh, end_time, hospital_id, start_time, null,
					null);
			qq.setPasswd(passwd);
			qq.setUsername(username);
			ImportSkThread ist = (ImportSkThread) request.getSession()
					.getAttribute("importSkThread");
			if (null == ist)
				try {
					ist = new ImportSkThread(qq);
					System.out.println(username+"登陆sk");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("err", "登陆医联网失败");
					getServletContext().getRequestDispatcher("/jsp/index.jsp?")
							.forward(request, response);
					return ;
				}
			else
				ist.setQ(qq);

			String skqueryTable = ist.getSkqueryTable();
			// List<RJReportInfo> reportlist = ss.getReportSK(username,
			// start_time,
			// end_time, kh);
			// String reportHtml = ReportUtils.getRJQuerListHtml(reportlist);
			// request.setAttribute("reportHtml", reportHtml);
			// String outinfo = "查询期间:" + start_time + "~" + end_time;
			request.setAttribute("skqueryTable", skqueryTable);
			getServletContext().getRequestDispatcher("/jsp/querysk.jsp?")
					.forward(request, response);
			request.getSession().setAttribute("importSkThread", ist);

			return;
		} else if (Const.RJQuerReport.equalsIgnoreCase(querytype)) {
			SignService ss = new SignService();
			String bgnum = (String) request.getParameter("bgnum");
			RJReport reportObj = ss.getSingleReport(username, bgnum);
			String reportHtml = ReportUtils.getRJReportHtml(reportObj);
			String outinfo = "报告编号:" + bgnum;
			request.setAttribute("outinfo", outinfo);
			request.setAttribute("reportHtml", reportHtml);
			getServletContext().getRequestDispatcher("/jsp/singlereport.jsp?")
					.forward(request, response);
		} else if (Const.inithospitallist.equalsIgnoreCase(querytype)) {
			try {
				Importer.updateHostpitalList();
				request.setAttribute("message", "更新医院名单成功!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				request.setAttribute("message", "更新医院名单失败!" + e.getMessage());
			}
			getServletContext().getRequestDispatcher("/jsp/message.jsp?")
					.forward(request, response);
		} /*
		 * else if ("INPUTSK".equalsIgnoreCase(querytype)) { // 获取报告列表 // 新建线程
		 * String message = ""; String cardId = request.getParameter("cards");
		 * // String start_time = request.getParameter("datestart"); // String
		 * end_time = request.getParameter("dateend"); String datestart_year =
		 * request.getParameter("datestart_year"); String datestart_month =
		 * request.getParameter("datestart_month"); String datestart_day =
		 * request.getParameter("datestart_day"); String start_time =
		 * datestart_year + "-" + datestart_month + "-" + datestart_day; String
		 * dateend_year = request.getParameter("dateend_year"); String
		 * dateend_month = request.getParameter("dateend_month"); String
		 * dateend_day = request.getParameter("dateend_day"); String end_time =
		 * dateend_year + "-" + dateend_month + "-" + dateend_day; String
		 * hospital_id = request.getParameter("hospital"); String mission_key =
		 * username + "," + passwd + "," + cardId + "," + start_time + "," +
		 * end_time + "," + hospital_id; System.out.println(mission_key); if
		 * (null != ImportSkThread.getThread(mission_key)) { message = username
		 * + "任务正在运行!请稍后"; } else { ImportSkThread thread = new
		 * ImportSkThread(mission_key);
		 * 
		 * ImportSkThread.addImport(thread); thread.deal(); int wholenum =
		 * thread.getWholesize(); if (0 == wholenum) message = "未找到该时间段的报告!";
		 * else message = "开始转移数据!读数报告总数量：" + wholenum; }
		 * 
		 * //
		 * 
		 * // 初始化导入对象 request.setAttribute(Const.userName, username);
		 * request.setAttribute("message", message);
		 * request.setAttribute("mission_key", mission_key); // 跳转到
		 * message_sk.jsp
		 * getServletContext().getRequestDispatcher("/jsp/message_sk.jsp?")
		 * .forward(request, response); }
		 */
		/*
		 * else if ("CHECK".equalsIgnoreCase(querytype)) {
		 * 
		 * String mission_key = request.getParameter("mission_key");
		 * System.out.println("query:" + mission_key);
		 * response.setContentType("text/html;charset=utf-8"); PrintWriter pw =
		 * response.getWriter(); if (null != ImportSkThread.getCounts()) {
		 * String jindu = ImportSkThread.getCounts().get(mission_key); if (null
		 * != jindu) {
		 * 
		 * pw.write(jindu);
		 * 
		 * } else {
		 * 
		 * pw.write("0"); } } else { pw.write("0"); }
		 * 
		 * }
		 */else if ("chart".equalsIgnoreCase(querytype)) {
			String querytypevalue = request.getParameter("querytypevalue");
			if (null != querytypevalue)
				querytypevalue = ReportUtils.getChinese(querytypevalue);

			String xlist = "[0]";
			String alltype = "";
			String qtype = "'指标'";

			String ylist = "[0]";
			String bigger = "[0]";
			String zbHtml = "";
			String smaller = "[0]";
			QueryService q = new QueryService(username);
			alltype = q.getAllDataTypeHtml();
			if (null == alltype)// 用户所有可以查的指标名称
				alltype = "";
			if (null != querytypevalue) {
				System.out.println("查询指标:" + querytypevalue);
				// querytypevalue = java.net.URLDecoder.decode(querytypevalue,
				// "UTF-8");
				System.out.println("查询指标:" + querytypevalue);
				q.getDataArray(querytypevalue);// 获得数组
				zbHtml = q.getZbHtml();// 获得表格
				if (null == zbHtml)
					zbHtml = "";
				if (null != q.getxList())// 获得曲线图数据
					xlist = q.getxList();// x坐标
				if (null != q.getyList())
					ylist = q.getyList();// y坐标

				if (null != q.getBigList())
					bigger = q.getBigList();
				if (null != q.getSmallList())
					smaller = q.getSmallList();// 指标上限下线

			}
			request.setAttribute("xlist", xlist);
			request.setAttribute("ylist", ylist);
			request.setAttribute("smaller", smaller);
			request.setAttribute("bigger", bigger);
			request.setAttribute("alltype", alltype);
			request.setAttribute("qtype", qtype);
			request.setAttribute("zbHtml", zbHtml);
			// 跳转到 message_sk.jsp
			getServletContext().getRequestDispatcher("/jsp/chart.jsp?")
					.forward(request, response);
		}else if ("chartreport".equalsIgnoreCase(querytype)) {
			String querytypevalue = request.getParameter("querytypevalue");
			if (null == querytypevalue)
				return;
			QueryService	q=new QueryService(username);
			ChartReport rt=q.getChartReport(querytypevalue);
			String timeline=rt.getTimeLine();
			String datatable=rt.getData(querytypevalue);
			request.setAttribute("timeline", timeline);
			request.setAttribute("datatable", datatable);
			// 跳转到 message_sk.jsp
			getServletContext().getRequestDispatcher("/jsp/chartreport.jsp?")
					.forward(request, response);
		}

	}
}